<script setup lang="ts">
import type { MultipleConditionSearchSchema, Widgets } from '../types'
import { get } from 'lodash-es'
import config from '../config'
import { ProvideParamsSymbol, ProvideSchemaSymbol } from '../types'
import IconClear from './IconClear.vue'
import RenderWidget from './RenderWidget.vue'

interface IEmit {
  (e: 'search'): void
  (e: 'delete', v: string): void
  (e: 'show'): void
  (e: 'hide'): void
}

interface IProps {
  widget: Widgets
}

const props = defineProps<IProps>()
const emit = defineEmits<IEmit>()

const params = inject<Ref<Record<string, any>>>(ProvideParamsSymbol)!
const schema = inject<MultipleConditionSearchSchema>(ProvideSchemaSymbol)!

const visible = ref(false)

const valueText = computed(() => {
  const val = get(params.value, [props.widget.field])
  if (props.widget.type === 'input') {
    return val
  }
  if (props.widget.type === 'select') {
    return (
      props.widget._optionsData?.find((item) => {
        return item.value === val
      })?.label || '-'
    )
  }
  return val
})

function handleSearch() {
  visible.value = false
  emit('search')
}

function handleDelete() {
  emit('delete', props.widget.field)
}
</script>

<template>
  <a-trigger
    v-model:popup-visible="visible"
    trigger="click"
    position="bl"
    :popup-offset="10"
    @show="emit('show')"
    @hide="emit('hide')"
  >
    <div class="content-tag">
      <span
        class="label"
        :style="{
          maxWidth: `${schema?.tag?.maxLabelWidth || config.tag.maxLabelWidth}px`,
        }"
      >
        {{ widget.label }}
      </span>
      <span class="divider">|</span>
      <span
        class="value"
        :style="{
          maxWidth: `${schema?.tag?.maxValueWidth || config.tag.maxValueWidth}px`,
        }"
      >
        {{ valueText }}
      </span>
      <icon-clear @click.stop="handleDelete" />
    </div>
    <template #content>
      <render-widget
        :widget="widget"
        @search="handleSearch"
      />
    </template>
  </a-trigger>
</template>

<style scoped lang="less">
.content-tag {
  display: inline-flex;
  align-items: center;
  height: 22px;
  line-height: 22px;
  padding: 6px;
  background: #f2f3f5;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  margin: 0 4px 0 0;
  .label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    color: #86909c;
  }
  .divider {
    color: #c9cdd4;
    margin: 0 4px;
  }
  .value {
    margin: 0 4px 0 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  svg {
    color: #86909c;
  }
}
</style>
